//
//  BDTransformViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/12.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDTransformViewController.h"

@interface BDTransformViewController () <UIAlertViewDelegate>
{
    NSString *phoneNum;
    NSMutableArray *_expressList;
    NSDictionary *companyDic;
    NSDictionary *expressStatusDic;
    NSString *companyName;
}

@property (weak, nonatomic) IBOutlet UILabel *expressStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *expressCompanyLabel;
@property (weak, nonatomic) IBOutlet UILabel *expressIDLabel;
@property (weak, nonatomic) IBOutlet UIButton *phoneButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;


@end

@implementation BDTransformViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"物流详情";
    
    companyDic = @{@"BD":@"背兜物流",
                   @"EMS":@"中国邮政EMS",
                   @"GTO":@"国通",
                   @"HTKY":@"汇通",
                   @"QFKD":@"全峰",
                   @"SFEXPRESS":@"顺风",
                   @"STO":@"申通",
                   @"TTKDEX":@"天天",
                   @"YTO":@"圆通",
                   @"YUNDA":@"韵达",
                   @"UC56":@"优速",
                   @"ZTO":@"中通"};
    
    expressStatusDic = @{@"ASSIGNED":@"已分配",
                         @"RECEIVING":@"取货中",
                         @"SENDING":@"送货中",
                         @"CINFIRM_RECEIPT":@"已签收"};
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self reloadData:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"正在查询"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?orderId=%@",
                     [BDNetworking shareInstance].baseUrl,
                     Express_Query,
                     self.orderId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"物流查询失败:%@",error);
            hud.labelText = @"物流查询失败";
            [hud hideAfterDelay:0.5];
        } else {
            [hud hideAfterDelay:0.5];
            NSLog(@"result = %@",results);
            NSDictionary *resultDic = (NSDictionary *)results;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                companyName = resultDic[@"company"];
                if (![companyName isEqual:[NSNull null]]) {
                    self.expressCompanyLabel.text = [NSString stringWithFormat:@"承运公司：%@",companyDic[companyName]];
                }
                NSString *status = resultDic[@"status"];
                if (![status isEqual:[NSNull null]]) {
                    self.expressStatusLabel.text = expressStatusDic[status];
                }
                NSString *expressId = resultDic[@"expressId"];
                if (![expressId isEqual:[NSNull null]]) {
                    self.expressIDLabel.text = [NSString stringWithFormat:@"运单编号：%@",expressId];
                }
                if (![companyName isEqualToString:@"BD"]) {
                    NSString *resultStr = resultDic[@"externalExpress"];
                    NSDictionary *resultDic = [NSString dictionaryWithJsonString:resultStr];
                    if ([resultDic valueForKey:@"result"] &&
                        [[resultDic valueForKey:@"result"] isKindOfClass:[NSDictionary class]]) {
                        _expressList = resultDic[@"result"][@"list"];
                    }
                } else {
                    _expressList = resultDic[@"bdExpresses"];
                }
                if (![_expressList isEqual:[NSNull null]]) {
                    [self.tableView reloadData];
                }
            });
        }
    }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _expressList.count > 0 ? _expressList.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_expressList.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tansformCell"];
        
        if (indexPath.row == 0) {
            [cell viewWithTag:201].hidden = YES;
            [cell viewWithTag:202].hidden = _expressList.count == 1 ? YES : NO;
        } else if (indexPath.row == _expressList.count -1) {
            [cell viewWithTag:202].hidden = YES;
        } else {
            [cell viewWithTag:201].hidden = NO;
            [cell viewWithTag:202].hidden = NO;
        }
        
        if ([companyName isEqualToString:@"BD"]) {
            UILabel *contentLabel = [(UILabel *)cell viewWithTag:101];
            contentLabel.text = _expressList[indexPath.row][@"content"];
            
            UILabel *timeLabel = [(UILabel *)cell viewWithTag:102];
            NSString *timeStr = _expressList[indexPath.row][@"time"];
            NSTimeInterval time = [timeStr doubleValue] / 1000;
            timeLabel.text = [NSString converToDateString:time formatter:@"yyyy-MM-dd HH:mm:ss"];
        } else {
            UILabel *contentLabel = [(UILabel *)cell viewWithTag:101];
            contentLabel.text = _expressList[indexPath.row][@"status"];
            
            UILabel *timeLabel = [(UILabel *)cell viewWithTag:102];
            timeLabel.text = _expressList[indexPath.row][@"time"];
        }
        
        
        
        return cell;
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tansformNoneCell"];
        
        return cell;
    }
}

#pragma mark - Tableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.scrollEnabled = _expressList.count > 0 ? YES : NO;
    return _expressList.count > 0 ? 80.0 : kScreen_Height - 258.0;
}

#pragma mark - UIAlertView delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
    }
}

#pragma mark - IBActions

- (IBAction)phoneButtonPressed:(UIButton *)sender {
    phoneNum = [NSString stringWithFormat:@"tel://%@",sender.currentTitle];
    NSString *promit = [NSString stringWithFormat:@"确定呼叫%@吗?",sender.currentTitle];
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"" message:promit delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alter.delegate = self;
    [alter show];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
